package com.hao.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * HttpClientUtil
 * Created by R.hao on 2017/4/18.
 */
public class HttpClientUtil {

    /**
     * 实例化HttpClient
     *
     * @param maxTotal
     * @param maxPerRoute
     * @param socketTimeout
     * @param connectTimeout
     * @param connectionRequestTimeout
     * @return
     */
    public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout,
                                              int connectionRequestTimeout) {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);
        cm.setDefaultMaxPerRoute(maxPerRoute);
        return HttpClients.custom().setConnectionManager(cm)
                .setDefaultRequestConfig(defaultRequestConfig).build();
    }

    public static String getResponseContent(HttpResponse response) throws Exception {
        return new String(read(response.getEntity().getContent()), "utf-8");
    }

    public static byte[] read(InputStream inputStream) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        copyTo(inputStream, os);
        return os.toByteArray();
    }

    private static boolean copyTo(InputStream is, OutputStream os) {
        byte[] bytes = new byte[1024];
        int len;
        try {
            while (true) {
                len = is.read(bytes);
                if (len != -1) {
                    os.write(bytes, 0, len);
                } else {
                    break;
                }
            }
            is.close();
            os.flush();
            os.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
